package com.example.invoke.service;

import com.example.invoke.util.RespEnum;
import com.example.invoke.util.RespObj;
import com.sun.istack.NotNull;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class CommonService {

    protected Map<String, Method> methodMap = new ConcurrentHashMap<>();

    public void initMethods (Object target) {
        if (methodMap.isEmpty()) {
            Method[] methods = target.getClass().getDeclaredMethods();
            for (Method m : methods) {
                methodMap.put(m.getName(), m);
            }
        }
    }

    protected String doHandle (@NotNull  Object target, Map source) {
        RespObj respObj = new RespObj();
        if (source.containsKey("action")) {
            initMethods(target);
            String action = String.valueOf(source.get("action"));
            String data = String.valueOf(source.get("data"));
            try {
                Method method = methodMap.get(action);
                if (method != null) {
                    String resp =  (String) method.invoke(target, data, respObj);
                    respObj.setMsg(resp);
                    respObj.setCode("200");
                }
            } catch (Exception e) {
                e.printStackTrace();
                RespEnum respEnum = RespEnum.getEnum(action);
                respObj.setCode(respEnum.getCode());
                respObj.setMsg(respEnum.getMsg());
            }
        } else {
            respObj.setMsg("action not found");
            respObj.setCode("503");
        }
        System.out.println(getClass().getName() + " result:" + respObj.toString());
        return respObj.toString();
    }

}
